<template>
  <CDialog
    title="下发日志"
    size="large"
    v-model:visible="dialogVisible"
    :loading="loading"
    :footer="false"
  >
    <div class="send-log-dialog-container g-pb15">
      <CTable
        :data-source="dataList"
        useDataSource
        :pagination="false"
        :border="true"
        :tableFieldsSetting="tableFieldsSetting"
      >
        <template
          #taskIssueStatusSlot="{ scope: { row } }: { scope: { row: GetListFillTaskResult } }"
        >
          <el-tag :type="renderTag(row.taskIssueStatus)" v-if="row.taskIssueStatus">{{
            FillInTaskLogStatusMap[row.taskIssueStatus] || row.taskIssueStatus
          }}</el-tag>
          <span v-else>-</span>
        </template>
        <template #taskStatusSlot="{ scope: { row } }: { scope: { row: GetListFillTaskResult } }">
          <el-tag :type="renderTag2(row.taskStatus)" v-if="row.taskStatus">{{
            FillInTaskStatusMap[row.taskStatus] || row.taskStatus
          }}</el-tag>
          <span v-else>-</span>
        </template>
        <template #opSlot="{ scope: { row } }: { scope: { row: GetListFillTaskResult } }">
          <!-- 已经发布或者已经撤回的任务，并且不能是审核通过的 -->
          <el-button
            text
            type="primary"
            @click="handleCancelReleased(row)"
            v-btnPermission="'ECI_FILL_TASK_DATA_WITHDRAW'"
            v-if="['ISSUED'].includes(row.taskIssueStatus) && !['PASS'].includes(row.taskStatus)"
            >撤回任务</el-button
          >
          <!-- 撤回的任务可以重新下发 -->
          <el-button
            text
            type="primary"
            @click="handleResend(row)"
            v-btnPermission="'ECI_FILL_TASK_DATA_DISPATCH'"
            v-if="row.taskIssueStatus === FillInTaskStatusEnum.WITHDRAW"
            >重新下发</el-button
          >
          <!-- 已过预计下发时间但是没有下发的，可以作下发补偿 -->
          <el-button
            text
            type="primary"
            @click="handleResend(row, false)"
            v-btnPermission="'ECI_FILL_TASK_DATA_DISPATCH'"
            v-if="row.taskIssueStatus === FillInTaskStatusEnum.WAIT_ISSUE"
            >下发</el-button
          >
          <!-- NOTE 已经通过审核的任务，想要修改数据 -->
          <el-button
            text
            type="primary"
            @click="handleRefill(row)"
            v-btnPermission="'ECI_FILL_TASK_DATA_DISPATCH'"
            v-if="['PASS'].includes(row.taskStatus)"
            >重启填报</el-button
          >
        </template>
      </CTable>
    </div>
  </CDialog>
</template>

<script lang="ts" setup name="SendLogDialog">
import { defineProps, withDefaults, defineEmits, computed, ref } from 'vue';
import { CDialog } from '@/components/CDialog';
import { CTable, CTableProps } from '@/components/CTable';
import {
  FillInTaskStatusEnum,
  FillInTaskLogStatusMap,
  FillInTaskStatusMap
} from '@/constants/enum';
import { watchEffect } from 'vue';
import { useMessage } from '@/hooks/useMessage';
import {
  getListFillTask,
  postWithdrawTask,
  postDispatchTask,
  postRestartTask
} from '@/apis/eci/inventory/inventory';
import type { GetListFillTaskResult } from '@/apis/eci/inventory/model/inventoryModel';

interface SendLogDialogProps {
  visible: boolean;
  inventoryNo: string;
}
interface SendLogDialogEmits {
  (e: 'update:visible', visible: boolean): void;
}
const props = withDefaults(defineProps<SendLogDialogProps>(), {});
const emits = defineEmits<SendLogDialogEmits>();
const dialogVisible = computed<boolean>({
  get: () => {
    return props.visible;
  },
  set: val => {
    emits('update:visible', val);
  }
});
watchEffect(() => {
  if (props.visible) {
    loadData();
  }
});
const { createMessage, createConfirm } = useMessage();

const loading = ref(false);
const dataList = ref<GetListFillTaskResult[]>([]);
async function loadData() {
  loading.value = true;
  try {
    dataList.value = await getListFillTask(props.inventoryNo);
    loading.value = false;
  } catch (error) {
    console.log('error', error);
    loading.value = false;
  }
}

const tableFieldsSetting: CTableProps['tableFieldsSetting'] = [
  {
    title: '数据周期',
    field: 'fillPeriod',
    minWidth: '90',
    align: 'center'
  },
  {
    title: '预计下发时间',
    field: 'expectIssueTime',
    minWidth: '170',
    align: 'center'
  },
  {
    title: '实际下发时间',
    field: 'taskIssueTime',
    minWidth: '170',
    align: 'center'
  },
  {
    title: '下发状态',
    field: 'taskStatus',
    slot: 'taskIssueStatusSlot',
    minWidth: '100',
    align: 'center'
  },
  {
    title: '填报任务状态',
    field: 'taskStatus',
    slot: 'taskStatusSlot',
    minWidth: '100',
    align: 'center'
  },
  {
    key: 'op',
    title: '操作',
    field: 'op',
    slot: 'opSlot',
    width: '120',
    align: 'center'
  }
];

const renderTag = (status: string) => {
  switch (status) {
    case FillInTaskStatusEnum.WITHDRAW:
      return 'danger';
    case FillInTaskStatusEnum.WAIT_ISSUE:
      return 'info';
    default:
      return 'success';
  }
};

const renderTag2 = (status: keyof typeof FillInTaskStatusEnum) => {
  switch (status) {
    case FillInTaskStatusEnum.PASS:
      return 'success';
    case FillInTaskStatusEnum.REJECT:
      return 'danger';
    case FillInTaskStatusEnum.FILLING:
      return '';
    case FillInTaskStatusEnum.WAIT_FILL:
      return 'info';
    case FillInTaskStatusEnum.WAIT_AUDIT:
      return 'warning';
    default:
      return 'info';
  }
};

/**
 * 撤回任务
 * @param row
 */
function handleCancelReleased(row: GetListFillTaskResult) {
  console.log('handleCancelReleased', row);
  createConfirm('是否撤回任务？', '任务撤回后，已填报的数据会被清除', {
    iconType: 'warning'
  }).then(async () => {
    loading.value = true;
    try {
      await postWithdrawTask(row.taskNo);
      createMessage.success('撤回任务成功！');
      loadData();
      loading.value = false;
    } catch (error) {
      console.log('error', error);
      loading.value = false;
    }
  });
}

/**
 * 重新下发/下发
 */
function handleResend(row: GetListFillTaskResult, isSend = true) {
  console.log('handleResend', row);
  createConfirm('提示', `是否${isSend ? '重新' : ''}下发任务？`, {
    iconType: isSend ? 'warning' : 'success'
  }).then(async () => {
    loading.value = true;
    try {
      await postDispatchTask(row.taskNo);
      createMessage.success(`${isSend ? '重新' : ''}下发成功！`);
      loadData();
      loading.value = false;
    } catch (error) {
      console.log('error', error);
      loading.value = false;
    }
  });
}

/**
 * 重新填报
 */
function handleRefill(row: GetListFillTaskResult) {
  createConfirm('是否重启填报？', '填报任务将会重新开启，已填报的数据不会删除', {
    iconType: 'warning'
  }).then(async () => {
    loading.value = true;
    try {
      await postRestartTask(row.taskNo);
      createMessage.success(`任务已退回到待填报状态！`);
      loadData();
      loading.value = false;
    } catch (error) {
      console.log('error', error);
      loading.value = false;
    }
  });
}
</script>
